import React, { Component } from 'react';
import IceContainer from '@icedesign/container';
import { Button, Form, Input, CascaderSelect, Select, Grid, Message, Upload, DatePicker } from '@alifd/next';
import { withRouter } from 'react-router-dom';
import PageHeadExcelAdd from '../../../../components/PageHeadExcelAdd';
import './index.scss';
import api from '../../../../utils/api';
import service from '../../../../utils/service';
import { unit } from '../../../../utils/setting';

const { Row, Col } = Grid;
const FormItem = Form.Item;
const selectSource = [
  { label: '镜片', value: '1' },
  { label: '非镜片', value: '0' },
];
const qiuSource = [
  { label: '球面', value: '球面' },
  { label: '非球面', value: '非球面' },
];
const jianSource = [
  { label: '渐进', value: '渐进' },
  { label: '非渐进', value: '非渐进' },
];
const formItemLayout = {
  labelCol: {
    fixedSpan: 5,
  },
  wrapperCol: {
    span: 13,
  },
  labelAlign: 'left',
};
const formItemLayout2 = {
  labelCol: {
    fixedSpan: 5,
  },
  wrapperCol: {
    span: 18,
  },
};
const formItemLayout3 = {
  labelCol: {
    fixedSpan: 10,
  },
  wrapperCol: {
    span: 12,
  },
};
function onPreview(info) {
  // console.log('onPreview callback : ', info);
}

function onChange(info) {
  // console.log('onChange callback : ', info);
}

function onError(file) {
  // console.log('onError callback : ', file);
}

// const headers = { token: sessionStorage.getItem('token') };
let classLabel = '';

function forLabel(value, data) {
  classLabel = data.label;
}

@withRouter
export default class Detail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      disabled: false,
      SupperDataList: [],
      GoodsTypeList: [],
      GoodsData: {
        goods_img: [],
        integral_rate: 1,
      },
      goods_bar_code: '',
      classLabel: '',
      goods_type: 1,
    };
  }
  onSuccess=(res, file) => {
    // console.log('onSuccess callback : ', res, file);
    let goods_img = [];
    goods_img = this.state.GoodsData.goods_img;
    goods_img.push(res.response.url.replace(api.uri, ''));
    this.setState(
      {
        GoodsData: {
          ...this.state.GoodsData,
          goods_img,
        },
      }
    );
  }
  onRemove= (file) => {
    // console.log('onRemove callback : ',res,file);
    const img = file.imgURL.replace(api.uri, '');
    const img2 = file.url.replace(api.uri, '');
    const goods_img = this.state.GoodsData.goods_img;
    // console.log(img);
    service({
      method: 'post',
      url: api.GoodsImgDel,
      data: { img },
    })
      .then((res) => {
        // console.log(res);
        if (res.data.code === 200) {
          Message.success('删除成功！');
          goods_img.splice(goods_img.indexOf(img2), 1);
        } else {
          Message.error(res.data.msg);
        }
      });
  }
  // 获取供应商列表
getSupperInfo= () => {
  service({
    method: 'get',
    url: api.GetSuperList,
  })
    .then((res) => {
      const data = res.data.list;
      const NewSList = [];
      data.forEach((item) => {
        NewSList.push({ label: item.name, value: item.id.toString() });
      });
      NewSList.sort((item1, item2) => {
        return item1.label.localeCompare(item2.label, 'cn');
      });
      this.setState(
        {
          SupperDataList: NewSList,
        }
      );
      // console.log(this.state.placeArr);
    });
}
// 获取商品类别列表
getGoodsTypeList= () => {
  service({
    method: 'get',
    url: api.GoodsTypeList,
  })
    .then((res) => {
      const data = res.data.class_list;
      // console.log(data.class_list);
      data.forEach((item) => {
        if (item.children) {
          item.children.sort((item1, item2) => {
            return item1.label.localeCompare(item2.label, 'cn');
          });
        }
      });
      this.setState(
        {
          GoodsTypeList: data,
        }
      );
    });
}

// 获取商品条码
getGoodsCode= () => {
  service({
    method: 'get',
    url: api.GoodsBarCode,
  })
    .then((res) => {
      if (res.data.code === 200) {
        this.setState(
          {
            GoodsData: {
              ...this.state.GoodsData,
              goods_bar_code: res.data.goods_bar_code,
            },

          }
        );
      }
    });
}
// 添加商品
AddGoods= () => {
  const data1 = this.state.GoodsData;
  service({
    method: 'post',
    url: api.GoodsChange,
    params: {
      act: 'add',
    },
    data: {
      goods_type: this.state.goods_type,
      ...data1,
    },
  })
    .then((res) => {
      if (res.data.code === 200) {
        Message.success('添加成功！');
        this.props.history.push('/basic/GoodsInfo');
      } else {
        Message.error('添加失败！');
      }
    });
}
componentDidMount() {
  this.getGoodsTypeList();
  this.getSupperInfo();
  this.getGoodsCode();
}
  // 方法
  // eslint-disable-next-line class-methods-use-this
  handleSelectFormChange = (value, action, item) => {
    if (value.goods_type === '1') {
      this.setState(
        {
          disabled: false,
          goods_type: value.goods_type,
          GoodsData: {
            goods_img: [],
            integral_rate: 1,
          },
        }
      );
    } else {
      this.setState(
        {
          disabled: true,
          goods_type: value.goods_type,
          GoodsData: {
            goods_img: [],
            integral_rate: 1,
          },
        });
    }
    // const data = Object.assign({}, this.state.GoodsData, value);
    // this.setState(
    //   {
    //     GoodsData: data,
    //   }
    // );
  }

  // this.setState(
  //   {
  //     classLabel: data.label,
  //   }
  // );

  // 表单变化时
handleGoodsAddFormChange= (value) => {
  const data = Object.assign({}, this.state.GoodsData, value);
  if (data.pro_time) {
    data.pro_time = new Date(data.pro_time).toLocaleDateString();
  }
  if (data.ope_time) {
    data.ope_time = new Date(data.ope_time).toLocaleDateString();
  }
  if (data.reg_time) {
    data.reg_time = new Date(data.reg_time).toLocaleDateString();
  }

  const nameArr = [];
  if (data.class_id !== undefined) {
    nameArr.push(classLabel);
  }
  if (data.model !== undefined) {
    nameArr.push(data.model);
  }
  if (data.color_layer !== undefined) {
    nameArr.push(data.color_layer);
  }
  if (data.refractivity !== undefined) {
    nameArr.push(data.refractivity);
  }
  if (data.is_sphere !== undefined) {
    nameArr.push(data.is_sphere);
  }
  if (data.is_gradual !== undefined) {
    nameArr.push(data.is_gradual);
  }
  if (data.case_value !== undefined) {
    nameArr.push(data.case_value);
  }
  data.goods_name = nameArr.join('-');
  this.setState(
    {
      GoodsData: data,
    }
  );
}

// 重置
handleReset= () => {
  history.go(0);
}
// 提交
handleSubmit= () => {
  this.AddGoods();
}
render() {
  // console.log(this.state.goods_type);
  return (
    <div width="100">
      <PageHeadExcelAdd title="添加商品" />
      <div>
        <IceContainer>
          <Form labelAlign="left" inline onChange={this.handleSelectFormChange}>
            <FormItem
              label="商品大类"
              labelAlign="left"
              size="large"
              style={{ marginBottom: '0' }}
            >
              <Select
                placeholder="请选择商品大类"
                id="goods_type"
                name="goods_type"
                size="large"
                dataSource={selectSource}
                autoWidth
                style={{ width: '200px' }}
                defaultValue="1"
                // onChange={this.handleBigSelectChage}
              />
            </FormItem>
          </Form>
        </IceContainer>
      </div>
      <IceContainer>
        <Row wrap>
          <Col span="12">
            {this.state.disabled === false ? (<Form
              style={styles.form}
              inline
              size="large"
              {...formItemLayout}
              value={this.state.GoodsData}
              onChange={this.handleGoodsAddFormChange}
            >
              <FormItem
                label="供应商"
                className="formItem"
              >
                <Select
                  dataSource={this.state.SupperDataList}
                  className="input200"
                  autoWidth
                  placeholder="请选择供应商"
                  name="s_id"
                />
              </FormItem>

              <FormItem

                label="商品类别"
                className="formItem"
              >
                <CascaderSelect
                  dataSource={this.state.GoodsTypeList}
                  expandTriggerType="hover"
                  className="input200"
                  displayRender={labels => labels[labels.length - 1]}
                  placeholder="请选择商品类别"
                  name="class_id"
                  onChange={forLabel}
                  changeOnSelect
                  listStyle={{ width: '180px' }}
                />
              </FormItem>

              <FormItem label="商品条码" className="formItemAll" {...formItemLayout2}>
                <Input
                  placeholder="请输入商品条码"
                  id="goods_bar_code"
                  name="goods_bar_code"
                  className="input200"
                  readOnly
                />
              </FormItem>
              <FormItem label="商品名称" className="formItemAll" {...formItemLayout2}>
                <Input
                  placeholder="请输入商品名称"
                  id="goods_name"
                  name="goods_name"
                  className="input"
                  readOnly
                />
              </FormItem>
              {/* <FormItem label="色散系数" className="formItem">
                <Input
                  placeholder="请输入色散系数"
                  id="dispersion"
                  name="dispersion"
                  className="input200"
                />
              </FormItem> */}
              <FormItem label="ADD" className="formItem">
                <Input
                  placeholder="请输入ADD"
                  id="ADD"
                  name="ADD"
                  className="input200"
                />
              </FormItem>

              <FormItem label="折射率" className="formItem">
                <Input
                  placeholder="请输入折射率"
                  id="refractivity"
                  name="refractivity"
                  className="input200"
                />
              </FormItem>
              <FormItem label="是否球面" className="formItem">
                <Select placeholder="请选择是否球面" className="input200" name="is_sphere" dataSource={qiuSource} />
              </FormItem>
              <FormItem label="是否渐进" className="formItem">
                <Select placeholder="请选择是否渐进" className="input200" name="is_gradual" dataSource={jianSource} />
              </FormItem>
              <FormItem label="型号" className="formItem">
                <Input
                  placeholder="请输入型号"
                  id="model"
                  name="model"
                  className="input200"
                />
              </FormItem>
              <FormItem label="特殊参数" className="formItem">
                <Input
                  placeholder="请输入特殊参数"
                  id="case_value"
                  name="case_value"
                />
              </FormItem>
              <FormItem label="颜色/镀层" className="formItem">
                <Input
                  placeholder="请输入颜色/镀层"
                  id="color_layer"
                  name="color_layer"
                />
              </FormItem>
              <FormItem label="规格" className="formItem">
                <Input
                  placeholder="请输入规格"
                  id="spec"
                  name="spec"
                />
              </FormItem>
              <FormItem label="单位" className="formItem">
                <Select
                  placeholder="请选择单位"
                  id="unit"
                  name="unit"
                  dataSource={unit}
                  style={{ width: '100%' }}
                />
              </FormItem>

              <FormItem label="零售价" className="formItem">
                <Input
                  placeholder="请输入零售价"
                  id="retail_price"
                  name="retail_price"
                />
              </FormItem>
              <FormItem label="进货价" className="formItem">
                <Input
                  placeholder="请输入进货价"
                  id="buying_price"
                  name="buying_price"
                />
              </FormItem>
              <FormItem label="折扣" className="formItem">
                <Input
                  placeholder="请输入折扣"
                  id="rebate"
                  name="rebate"
                />
              </FormItem>
              <FormItem label="积分率" className="formItem">
                <Input
                  placeholder="请输入积分率"
                  id="integral_rate"
                  name="integral_rate"
                  defaultValue="1"
                />
              </FormItem>
                                              </Form>) : (<Form
              style={styles.form}
              inline
              size="large"
              {...formItemLayout}
              value={this.state.GoodsData}
              onChange={this.handleGoodsAddFormChange}
            >
              <FormItem
                                                  label="供应商"
                                                  className="formItem"
                                                >
                                                  <Select
                  dataSource={this.state.SupperDataList}
                  className="input200"
                  autoWidth
                  placeholder="请选择供应商"
                  name="s_id"
                />
                                                </FormItem>

              <FormItem

                                                  label="商品类别"
                                                  className="formItem"
                                                >
                                                  <CascaderSelect
                  dataSource={this.state.GoodsTypeList}
                  expandTriggerType="hover"
                  className="input200"
                  displayRender={labels => labels[labels.length - 1]}
                  placeholder="请选择商品类别"
                  onChange={forLabel}
                  name="class_id"
                  listStyle={{ width: '180px' }}
                />
                                                </FormItem>

              <FormItem label="商品条码" className="formItemAll" {...formItemLayout2}>
                                                  <Input
                  placeholder="请输入商品条码"
                  id="goods_bar_code"
                  name="goods_bar_code"
                  className="input200"
                  readOnly
                />
                                                </FormItem>
              <FormItem label="商品名称" className="formItemAll" {...formItemLayout2}>
                                                  <Input
                  placeholder="请输入商品名称"
                  id="goods_name"
                  name="goods_name"
                  className="input"
                  readOnly
                />
                                                </FormItem>
              {/* <FormItem label="色散系数" className="formItem">
                <Input
                  placeholder="请输入色散系数"
                  id="dispersion"
                  name="dispersion"
                  className="input200"
                />
              </FormItem> */}
              {/* <FormItem label="ADD" className="formItem">
                <Input
                  placeholder="请输入ADD"
                  id="ADD"
                  name="ADD"
                  className="input200"
                />
              </FormItem>

              <FormItem label="折射率" className="formItem">
                <Input
                  placeholder="请输入折射率"
                  id="refractivity"
                  name="refractivity"
                  className="input200"
                />
              </FormItem>
              <FormItem label="选择球面" className="formItem">
                <Select placeholder="请选择是否球面" className="input200" name="is_sphere" dataSource={qiuSource} />
              </FormItem>
              <FormItem label="是否渐进" className="formItem">
                <Select placeholder="请选择是否渐进" className="input200" name="is_gradual" dataSource={jianSource} />
              </FormItem> */}
              <FormItem label="型号" className="formItem">
                                                  <Input
                  placeholder="请输入型号"
                  id="model"
                  name="model"
                  className="input200"
                />
                                                </FormItem>
              <FormItem label="特殊参数" className="formItem">
                                                  <Input
                  placeholder="请输入特殊参数"
                  id="case_value"
                  name="case_value"
                />
                                                </FormItem>
              <FormItem label="颜色/镀层" className="formItem">
                                                  <Input
                  placeholder="请输入颜色/镀层"
                  id="color_layer"
                  name="color_layer"
                />
                                                </FormItem>
              <FormItem label="规格" className="formItem">
                                                  <Input
                  placeholder="请输入规格"
                  id="spec"
                  name="spec"
                />
                                                </FormItem>
              <FormItem label="单位" className="formItem">
                                                  <Select
                  placeholder="请选择单位"
                  id="unit"
                  name="unit"
                  dataSource={unit}
                  style={{ width: '100%' }}
                />
                                                </FormItem>

              <FormItem label="零售价" className="formItem">
                                                  <Input
                  placeholder="请输入零售价"
                  id="retail_price"
                  name="retail_price"
                />
                                                </FormItem>
              <FormItem label="进货价" className="formItem">
                                                  <Input
                  placeholder="请输入进货价"
                  id="buying_price"
                  name="buying_price"
                />
                                                </FormItem>
              <FormItem label="折扣" className="formItem">
                                                  <Input
                  placeholder="请输入折扣"
                  id="rebate"
                  name="rebate"
                />
                                                </FormItem>
              <FormItem label="积分率" className="formItem">
                                                  <Input
                  placeholder="请输入积分率"
                  id="integral_rate"
                  name="integral_rate"
                  defaultValue="1"
                />
                                                </FormItem>
                        </Form>)}
            <br />
            <Upload.Card
              style={{ float: 'left' }}
              listType="card"
              action={api.GoodsImg}
              // headers={{ token: sessionStorage.getItem('token') }}
              accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp"
              formatter={(res, file) => {
              return {
               success: res.code === 200,
               url: `${api.uri}${res.img_url}`,
             };
            }}
              onPreview={onPreview}
              onChange={onChange}
              onSuccess={this.onSuccess}
              onError={onError}
              onRemove={this.onRemove}
            >

            </Upload.Card>
          </Col>

          <Col span="12" style={{ borderLeft: '1px solid #ccc' }}>
            <h3 className="r-title">医疗器械生产经营企业资料</h3>
            <Form
              style={styles.form}
              inline
              size="large"
              className="form2"
              id="form2"
              {...formItemLayout3}
              onChange={this.handleGoodsAddFormChange}
            >
              <FormItem
                label=" 生产企业"
                className="formItemAll"
                {...formItemLayout3}
              >
                <Input
                  placeholder="请输入生产企业"
                  id="esta_person"
                  name="esta_person"
                  size="large"
                  disabled={this.state.disabled}
                />
              </FormItem>
              <FormItem label="生产许可证号" className="formItemAll">
                <Input
                  placeholder="请输入生产许可证"
                  id="pro_number"
                  name="pro_number"
                  disabled={this.state.disabled}
                />
              </FormItem>
              <FormItem label="生产许可证有效期至" className="formItemAll">
                <DatePicker
                  // placeholder="2019-01-01"
                  id="pro_time"
                  name="pro_time"
                  disabled={this.state.disabled}
                  style={{ width: '100%' }}
                  hasClear={false}
                />
              </FormItem>
              <FormItem label="经营许可证号" className="formItemAll">
                <Input
                  placeholder="请输入经营许可证号"
                  id="ope_number"
                  name="ope_number"
                  disabled={this.state.disabled}
                />
              </FormItem>
              <FormItem label="经营许可证有效期至" className="formItemAll">
                <DatePicker
                  // placeholder="2019-01-01"
                  id="ope_time"
                  name="ope_time"
                  disabled={this.state.disabled}
                  style={{ width: '100%' }}
                  hasClear={false}
                />
              </FormItem>

              <FormItem label="注册证号" className="formItemAll">
                <Input
                  placeholder="请输入注册证号"
                  id="reg_number"
                  name="reg_number"
                  disabled={this.state.disabled}
                />
              </FormItem>
              <FormItem label="注册证有效期至" className="formItemAll">
                <DatePicker
                  // placeholder="2019-01-01"
                  id="reg_time"
                  name="reg_time"
                  disabled={this.state.disabled}
                  style={{ width: '100%' }}
                  hasClear={false}
                />
              </FormItem>
              <FormItem label="有效期（月）" className="formItemAll">
                <Input
                  placeholder="请输入有效期"
                  id="term_time"
                  name="term_time"
                  disabled={this.state.disabled}
                />
              </FormItem>
              <FormItem
                label="国家医疗器械类别编号"
                className="formItemAll"
              >
                <Input
                  placeholder="请输入国家医疗器械类别编号"
                  id="medical_number"
                  name="medical_number"
                  disabled={this.state.disabled}
                />
              </FormItem>
              <FormItem
                label="医疗器械名称"
                className="formItemAll"
              >
                <Input
                  placeholder="请输入医疗器械名称"
                  id="medical_name"
                  name="medical_name"
                  disabled={this.state.disabled}
                />
              </FormItem>
              <FormItem label="预留1" className="formItemAll">
                <Input
                  placeholder=""
                  id="m_reserve_one"
                  name="m_reserve_one"
                  disabled={this.state.disabled}
                />
              </FormItem>
              <FormItem label="预留2" className="formItemAll">
                <Input
                  placeholder=""
                  id="m_reserve_two"
                  name="m_reserve_two"
                  disabled={this.state.disabled}
                />
              </FormItem>
            </Form>
          </Col>
        </Row>
        <Row>
          <Col style={{ textAlign: 'center', marginTop: '20px' }}>
            <Button
              type="primary"
              style={{ marginRight: '40px' }}
              className="sub-btn"
              id="subBtn"
              onClick={this.handleSubmit}
            >
                保存
            </Button>
            <Button type="primary" className="cancel-btn" id="cancelBtn" onClick={this.handleReset}>
                重置
            </Button>
          </Col>
        </Row>
      </IceContainer>
    </div>
  );
}
}

const styles = {
  form: {
    backgroundColor: '#fff',
    overflow: 'hidden',
  },
  separator: {
    margin: '0 auto',
    width: '2px',
    height: '100%',
    backgroundColor: '#E6E7EB',
  },
};
